<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <input type="file" id="fileInput" accept="video/mp4" />
  <video id="video" controls></video>
  <button id="playButton">gpt 本地视频循环切片到 mediaSource</button>
</body>
<script type="text/javascript">
const fileInput = document.getElementById("fileInput");
const video = document.getElementById("video");
const playButton = document.getElementById("playButton");

fileInput.addEventListener("change", (event) => {
  const file = event.target.files[0];
  if (!file) return;

  // 创建 MediaSource 对象
  const mediaSource = new MediaSource();
  video.src = URL.createObjectURL(mediaSource);

  mediaSource.addEventListener("sourceopen", () => {
    console.log("MediaSource opened");

    const mimeType = 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"'; // 确保 mimeType 与文件兼容

    if (!MediaSource.isTypeSupported(mimeType)) {
      console.error("Unsupported MIME type:", mimeType);
      return;
    }

    const sourceBuffer = mediaSource.addSourceBuffer(mimeType);

    let fileChunks = [];
    let offset = 0;
    const chunkSize = 64 * 1024; // 每次读取的大小

    // 分段读取文件并添加到 SourceBuffer
    const reader = new FileReader();

    reader.onload = (e) => {
      console.log("Appending buffer...");
      sourceBuffer.appendBuffer(e.target.result);
      offset += e.target.result.byteLength;

      // 继续读取文件直到全部加载完
      if (offset < file.size) {
        readNextChunk();
      } else {
        // 所有数据加载完毕后，检查 SourceBuffer 是否完成更新
        checkSourceBufferUpdateComplete();
      }
    };

    // 读取下一个文件块
    function readNextChunk() {
      const slice = file.slice(offset, offset + chunkSize);
      reader.readAsArrayBuffer(slice);
    }

    // 等待 SourceBuffer 更新完成后调用 endOfStream
    function checkSourceBufferUpdateComplete() {
      if (!sourceBuffer.updating) {
        console.log("All data appended. Calling endOfStream()");
        mediaSource.endOfStream();
      } else {
        // 如果 SourceBuffer 还在更新，则延迟调用 endOfStream
        console.log("SourceBuffer is still updating. Retrying...");
        setTimeout(checkSourceBufferUpdateComplete, 50);
      }
    }

    // 开始读取文件
    readNextChunk();

    // SourceBuffer updateend 事件处理
    sourceBuffer.addEventListener("updateend", () => {
      console.log("SourceBuffer update complete");
    });
  });
});

// 播放按钮点击事件
playButton.addEventListener("click", () => {
  console.log("Play button clicked");
  video.play().catch((err) => {
    console.error("Playback error:", err);
  });
});
</script>
</html>
